package com.example.rabbitmq_study.HelloWorld;

import com.example.rabbitmq_study.util.RabbitmqUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/7/28 15:45
 */
public class Consumer {
    /*
        消费消息
     */
    public static void main(String[] args) throws IOException, TimeoutException {
        //获取连接对象
        Connection connection = RabbitmqUtil.getConnection();

        //获取连接中的通道
        Channel channel = connection.createChannel();

        //声明队列
        channel.queueDeclare("hello"/*队列名*/, true/*持久化*/, false/*独占*/, false/*自动删除*/, null/*map额外参数*/);

        //创建消费者接收到消息后的回调方法
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            //覆盖方法，因为该类中的方法都是空实现
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //获取交换机
                String exchange = envelope.getExchange();
                //消息id，mq在channel中用来标识消息的id，如果获取到该id表明也获取到了该id的消息所以可用于确认消息已接收
                long deliveryTag = envelope.getDeliveryTag();
                //将字节类型的消息转换成字符串
                String string = new String(body, "utf-8");

                System.out.println("receive deliveryTag:" + deliveryTag);
                System.out.println("receive message:" + string);
            }
        };

        channel.basicConsume("hello",  true, "flag-1", defaultConsumer);
    }
}
